<?php
namespace app\admin\controller;
use think\Controller;
use think\captcha\Captcha;
use think\Request;//请求类
use think\Cookie;
use think\Cache;

class Login extends Controller
{
    public function login()
    {	
    	if (Cookie::has('id')){
    		$this->redirect('Index/index');
    	}

    	if (request()->isPost()){
    		//验证验证码
    		//验证账户密码
    		$info = request()->Post();
    		// dump($info);die;
    		$username = $info['data']['username'];
    		$password = $info['data']['password'];
    		$code = $info['data']['captcha'];
    		
    		if(!$this->captcha_check($code)){
    			return $this->error('验证码错误');
    		}

    		$result = model('Admin')->check_login($username,$password);
    		return $result;
    	}else{
    		return $this->fetch();
    	}
        
    }

    public function verify()
    {

    	$config = [

        'fontSize' => 26,
        // 验证码字体大小(px)
        'useCurve' => false,
        // 是否画混淆曲线
        'useNoise' => false,
        // 是否添加杂点
        'imageH'   => 0,
        // 验证码图片高度
        'imageW'   => 0,
        // 验证码图片宽度
        'length'   => 3,
        // 验证码位数
        'fontttf'  => '',
        // 验证码字体，不设置随机获取
        'bg'       => [243, 251, 254]
        // 背景颜色
    	];

        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    public function captcha_check($code){
    	$captcha = new Captcha();
    	return $captcha->check($code);
    }

    public function logout(){
      // Cookie('id',null);
      // $this->redirect('Login/login');
      
      //读取cookie
      $id = Cookie::get('id');
      //删除缓存
      Cache::rm('user_'.$id);
      //删除cookie
      Cookie::delete('admin'); 
      Cookie::delete('username');
      Cookie::delete('id'); 

      $this->redirect('Login/login');
    } 
}
